package com.tx.studentManager.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.tx.studentManager.qo.BaseQo;
import com.tx.studentManager.dao.base.HibernateGenericDao;
import com.tx.studentManager.model.Page;
import com.tx.studentManager.model.Role;
import com.tx.studentManager.model.User;
import com.tx.studentManager.qo.UserQO;


@Repository("userDao")
public class UserDao extends HibernateGenericDao<User, Integer,UserQO> {

	@Override
	protected Criteria buildCriteria(Criteria criteria, UserQO qo) {
		//查询具有某一角色的用户
		if (qo.getRoleId()!=null) {
			criteria.createCriteria("role").add(Restrictions.eq("roleId", qo.getRoleId()));
		}
		return criteria;
	}
	
	@Override
	public List<User> queryList(UserQO qo) {
		logger.debug("override BaseDao.queryList(BaseQo)");
		List<User> userList=super.queryList(qo);
		ifInitAll(qo, userList);
		return userList;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Page queryListByPage(Page page) {
		logger.debug("override BaseDao.findListByPage(Page)");
		Page resultPage= super.queryListByPage(page);
		ifInitAll((BaseQo) page.getCondition(), (List<User>) resultPage.getList());
		return resultPage;
	}

	/**
	 * 初始化加载懒加载的实例
	 * @param qo
	 * @param users
	 */
	private void ifInitAll(BaseQo qo,List<User>users){
		if (qo.isInitAll()) {
			for (User user : users) {
				logger.debug("lazy load user.roles");
				Role role=user.getRole();
				Hibernate.initialize(role);
			}
			
		}
	}
}
